/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.worldscale.xp.wslib.im.jabber;

/**
 *
 * @author Kun
 */
public final class JabberID {

    private final String mUser;
    private final String mHost;
    private final String mResource;

    public JabberID(final String user, final String host, final String res) {
        mUser = user;
        mHost = host;
        mResource = (res == null) ? "" : res;
    }

    public JabberID(final String jid) {
        String user, host, res, hr;
        final int i1, i2;
        i1 = jid.indexOf('@');
        if (i1 < 0) {
            user = "";
            hr = jid;
        } else {
            user = jid.substring(0, i1);
            hr = jid.substring(i1 + 1);
        }
        i2 = hr.indexOf('/');
        if (i2 < 0) {
            host = hr;
            res = "";
        } else {
            host = hr.substring(0, i2);
            res = hr.substring(i2 + 1);
        }
        mUser = user;
        mHost = host;
        mResource = res;
    }

    public String getUser() {
        return mUser;
    }

    public String getHost() {
        return mHost;
    }

    public String getResource() {
        return mResource;
    }

    @Override
    public String toString() {
        if (mResource == null) {
            return (mUser + '@' + mHost);
        }
        if (mResource.length() <= 0) {
            return (mUser + '@' + mHost);
        }
        return (mUser + '@' + mHost + '/' + mResource);
    }

    public JabberID getPureJID() {
        if (this.mResource == null) {
            return this;
        }
        if (this.mResource.equals("")) {
            return this;
        }
        return new JabberID(this.mUser, this.mHost, null);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (!this.getClass().equals(obj.getClass())) {
            return false;
        }
        return (this.toString().equals(obj.toString()));
    }

    public boolean equalsIgnoreResource(JabberID jid) {
        if (jid == null) {
            return false;
        }
        return (this.mHost.equals(jid.mHost) && this.mUser.equals(jid.mUser));
    }
}
